<template>
  <div v-loading="loading">
    <div v-if="naireList == undefined || naireList.length == 0" align="center">
      <br />
      <h1>诊断专家组正在为您定制专属调研问卷,将请期待……</h1>
    </div>
    <div v-else>
      <el-button
        type="success"
        round
        size="medium "
        @click.native="handleBegin()"
        style="
          display: block;
          float: right;
          margin-right: 40px;
          position: relative;
          z-index: 1;
        "
        >继续答题 <i class="el-icon-right"
      /></el-button>

      <el-divider
        ><i class="el-icon-info">蓝色为已作答,灰色为未作答</i></el-divider
      >
      <my-tree
        :treedata="naireList"
        :naireId="parseFloat(queryParams.naireId)"
        @changeCommit="canHandleSubmit"
      ></my-tree>

      <el-divider
        ><i class="el-icon-info">蓝色为已作答,灰色为未作答</i></el-divider
      >
    </div>
    <el-dialog
      title="重要提醒"
      :visible.sync="dialogVisible"
      width="30%"
      center
    >
      <span>请确认所有问题已回答完毕</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDone">确 定</el-button>
      </span>
    </el-dialog>
    <div align="center">
      <el-button
        v-if="!isUnique"
        type="primary"
        round
        size="medium "
        @click.native="handleConfirm()"
        style="display: block"
      >
        结束答题 <i class="el-icon-right"
      /></el-button>
      <el-button
        v-else-if="isUnique && canSubmit && $route.query.isDiagnosis != 1"
        type="primary"
        round
        size="medium "
        @click.native="handleSubmit()"
        style="display: block"
      >
        提交测评表 <i class="el-icon-right"
      /></el-button>
      <el-button
        v-else-if="isUnique && $route.query.isDiagnosis == 1"
        type="primary"
        round
        size="medium "
        @click.native="handleDiagnosisSubmit()"
        style="display: block"
      >
        提交现场诊断问卷 <i class="el-icon-right"
      /></el-button>
      <h4 v-else style="height: 30px">请先全部回答后再提交</h4>
    </div>
  </div>
</template>
<script>
import MyTree from "./QuestionOverviewItem";
import { treelistQuestionWithRecord } from "@/api/system/question";
import { addTask, endTask, endDiagnosisTask } from "@/api/system/diagnosistask";
export default {
  components: { MyTree },
  data() {
    return {
      loading: false,
      canSubmit: true,
      //是否是测评表
      isUnique: false,
      dialogVisible: false,
      activeNames: ["1", "2", "3", "4"],
      tabPosition: "left",
      naireList: "",
      queryParams: {
        companyId: this.$route.query.compId || this.$store.state.user.compId,
        naireId: undefined,
      },
    };
  },
  created() {
    if (this.$route.query.naireId)
      this.queryParams.naireId = this.$route.query.naireId;
    // console.log('queryParams',this.queryParams.naireId)

    if (this.$route.query.compId) this.isUnique = true;

    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      treelistQuestionWithRecord(this.queryParams).then((response) => {
        this.naireList = response.data;
        this.loading = false;
        this.naireList.map((data) =>
          data.children.map(
            (items) =>
              items.hasOwnProperty("children") &&
              items.children.map(
                (questionList) =>
                  (questionList.questions = this.judgeMoreLevel(
                    questionList.questions
                  ))
              )
          )
        );
        // console.log(this.naireList);
        // this.naireList.forEach((question) => {
        //   if (
        //     question.records &&
        //     question.records.length > 0 &&
        //     judge(question.records)
        //   ) {
        //     console.log("first");
        //   } else {
        //     console.log("secs");
        //   }
        // });
      });
    },

    judgeMoreLevel(list) {
      let qmaps = new Map();
      let questionList = [];
      this.drawingList?.forEach((item) => {
        if (qmaps.has(parseInt(item.level))) {
          let qarr = qmaps.get(parseInt(item.level));
          qarr.push(item);
          qmaps.set(parseInt(item.level), qarr);
        } else {
          qmaps.set(parseInt(item.level), [item]);
          qmaps.set(parseInt(item.level), [item]);
        }
      });

      if (qmaps.has(0)) {
        questionList = questionList.concat(...qmaps.get(0));
      }
      questionList = questionList.concat(...qmaps.get(1));

      for (let level = 2; level <= 5; level++) {
        if (qmaps.has(level)) {
          if (this.judgeSelectTrue(qmaps.get(level - 1))) {
            questionList = questionList.concat(...qmaps.get(level));
          } else {
            break;
          }
        }
      }
      return questionList;
    },

    judgeSelectTrue(arr, field = "answer", isTrue = "0") {
      let flag = true;
      arr.forEach((items) => {
        if (items.hasOwnProperty("records") && items.records.length > 0) {
          items.records.forEach((item) => {
            console.log(
              item.createBy,
              this.$store.state.user.name,
              "this.$store.state.user.name"
            );
            if (
              item.userId !== this.$store.state.user.userId &&
              item[field] != isTrue
            ) {
              flag = false;
            }
          });
        } else {
          flag = false;
        }
      });
      return flag;
    },

    handleBegin() {
      // console.log('naireId',this.queryParams.naireId)
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        name: "showQuestionnairexczd",
        query: {
          naireId: this.queryParams.naireId,
          compId: this.$route.query.compId,
          domain: this.$route.query.domain || 12,
          isDiagnosis: this.$route.query.isDiagnosis,
        },
      });
    },
    handleConfirm() {
      this.dialogVisible = true;
    },
    handleDone() {
      this.dialogVisible = true;
      let form = {};
      form.companyId = this.queryParams.companyId;
      form.naireId = this.queryParams.naireId;
      form.status = "2";

      addTask(form).then((response) => {
        this.$modal.msgSuccess("提交成功");
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.push({
          name: "NaireList",
        });
      });
    },
    handleSubmit() {
      endTask(this.queryParams.companyId).then((response) => {
        this.$modal.msgSuccess("提交测评表成功");
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.push({
          path: "/expert/expertdiagnosis",
        });
      });
    },
    handleDiagnosisSubmit() {
      endDiagnosisTask(this.queryParams.companyId).then((response) => {
        this.$modal.msgSuccess("提交现场诊断问卷成功");
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.push({
          name: "useTemplete",
          query: {
            naireId: this.queryParams.naireId,
            compId: this.$route.query.compId,
            domain: this.$route.query.domain || 12,
            isDiagnosis: this.$route.query.isDiagnosis,
          },
        });
      });
    },
    canHandleSubmit(val) {
      this.canSubmit = val;
      console.log(this.canSubmit, val);
    },
  },
};
</script>
